<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="基础信息" name="first">
      <div class="Modal">
        <div>
          <FormPanel
            ref="formPanel"
            :list="formList"
            :cols="3"
            :formType="type"
            labelWidth="100"
            :isSubmitBtn="false"
            @formChange="formChangeHandle"
          />
        </div>
        <div
          :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
        >
          <el-button @click="closeDialog">取 消</el-button>
          <AjaxButton :click="saveDialog" type="primary">确 定</AjaxButton>
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane v-if="beijing" label="线索评级信息">
      <clueLevelModel :rowData="rowData" />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { addNewClue } from '@/api/potenCus/customer/cluesQuery';
import { getBrandList, getSeriesList, getModelList, getPackageList, getOptionList, getColorsList } from '@/api/potenCus/basedata/searchTestDriveCars';
import { getUserInfo } from '@/api/potenCus/customer/exhibition';
import { queryClueSourceList } from '@/api/potenCus/customer/potenCusManage';
import { getlistAllData } from '@/api/common/org/dealerCompany'; //城市接口
import { phone, formatDates, formatDat, forDates } from '@/utils/validate';
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { getDataType, getAppId } from '@/assets/js/auth'; 
import  clueLevelModel  from '../potenCusManageOEM/clueLevelModel';

export default {
  name: 'queryModel',
  mixins: [dictionary, authority],
   components: {
    clueLevelModel
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return { 
      activeName:'first',
      beijing:getAppId()=="beijing"?true:false, 
      dataType: getDataType('dataType'),
      formList: this.createFormList(),
      province_id: '',
      city_id: '',
      consultsList: []
    };
  },
  created() {
    this.init();
    this.getClueTree();
    this.getCityList();
    this.getDictBrandList();
  },
  mounted() {

    //af备注置灰 
    if (getAppId() == 'arcfox') { 
      this.formList.find(x => x.fieldName == 'remark').disabled = true; 
    } 
  },
  methods: {
    async init() {
      await getUserInfo().then(res => {
        if (res.resultCode == 200) {
          this.userId = res.data.userInfo.userId;
          // console.log('self',this.userId)
        }
      });
      console.log('线索管理rowData', this.rowData, this.type);
      console.log(this.dataType);
      if (this.type == 'show') {
        this.formList.forEach(x => {
          if (x.fieldName == 'inteBrand') {
            x.initialValue = this.rowData['inteBrandName'];
          } else if (x.fieldName == 'telemarketingNo') {
            x.initialValue = this.rowData['consultantName'];
          } else if (x.fieldName == 'inteBrand') {
            x.initialValue = this.rowData['inteBrandName'];
          } else if (x.fieldName == 'inteBrand') {
            x.initialValue = this.rowData['inteBrandName'];
          } else if (x.fieldName == 'clueSourceRemark') {
            x.initialValue = this.rowData['sourceRemark'];
          } else if (x.fieldName == 'clueSourceId') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['clueSourceName'];
          } else if (x.fieldName == 'inteCarSeries') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['inteCarSeriesName'];
          } else if (x.fieldName == 'inteCarType') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['inteCarTypeName'];
          } else if (x.fieldName == 'inteYearStyle') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['inteYearStyleName'];
          } else if (x.fieldName == 'inteOption') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['inteOptionName'];
          } else if (x.fieldName == 'inteColour') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['inteColourName'];
          } else if (x.fieldName == 'provinceId') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['provinceName'];
          } else if (x.fieldName == 'city') {
            x.type = 'INPUT';
            x.initialValue = this.rowData['cityName'];
          } else if (x.fieldName == 'acquisitionTime') {
            x.hidden = true;
          } else if (x.fieldName == 'exactdate') {
            x.hidden = true;
          } else if (x.fieldName == 'bookingDate') {
            x.hidden = true;
          } else {
            x.initialValue = this.rowData[x.fieldName];
          }
        });
      } else {
        // 查询所属顾问
        // let roleType = this.dataType === 'clue' ? '10061012':'10061012,10061015';
        // this.getConsultant(1,roleType).then((result) => {

        // 2020/1/7 新增只可选择网销顾问  不查重
        this.getConsultant(0, 10061012).then(result => {
          console.log('顾问数据', result);
          this.consultsList = result;
          this.formList.find(item => item.fieldName === 'telemarketingNo').itemList = result;
        });
      }

      // this.formList.find(x => x.fieldName ==='telemarketingNo').initialValue = this.userId
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'customerType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('1523'),
          change: val => {
            console.log('val', val);
            if (val === 15231001) {
              this.formList.find(item => item.fieldName === 'customerType').initialValue = 15231001;
              // this.formList.find(item => item.fieldName ==='customerName').label = '客户名称'
              this.formList.find(item => item.fieldName === 'contactName').hidden = true;
              this.formList.find(item => item.fieldName === 'gender').label = '性别';
              this.formList.find(item => item.fieldName === 'mobilePhone').hidden = false;
              this.formList.find(item => item.fieldName === 'contactPhone').hidden = true;
            }
            if (val === 15231003) {
              // this.contactName == this.formList.find(item => item.fieldName ==='customerName').initialValue
              this.formList.find(item => item.fieldName === 'customerType').initialValue = 15231003;
              // this.formList.find(item => item.fieldName ==='customerName').label = '联系人姓名'
              this.formList.find(item => item.fieldName === 'contactName').hidden = false;
              this.formList.find(item => item.fieldName === 'gender').label = '联系人性别';
              this.formList.find(item => item.fieldName === 'mobilePhone').hidden = true;
              this.formList.find(item => item.fieldName === 'contactPhone').hidden = false;
            }
          },
          rules: [{ required: true, message: '请选择客户类型', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          maxlength: 30,
          placeholder: '请输入',
          hidden: false,
          rules: [{ required: true, message: '请输入客户名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '联系人姓名',
          fieldName: 'contactName',
          placeholder: '请输入',
          hidden: true,
          rules: [{ required: true, message: '请输入联系人姓名', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '性别',
          fieldName: 'gender',
          placeholder: '请选择',
          hidden: false,
          itemList: this.createDictList('1002')
          // rules: [{ required: true, message: '请选择性别', trigger: 'change' }],
        },
        {
          type: 'INPUT',
          label: '手机号码',
          fieldName: 'mobilePhone',
          placeholder: '请输入',
          maxlength: 11,
          // disabled: this.type === 'addForbase'?true:false,
          rules: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { trigger: 'blur', validator: phone }
          ]
        },
        {
          type: 'INPUT',
          label: '联系人手机',
          fieldName: 'contactPhone',
          placeholder: '请输入',
          maxlength: 11,
          hidden: true,
          rules: [
            { required: true, message: '请输入联系人手机号', trigger: 'blur' },
            { trigger: 'blur', validator: phone }
          ]
        },
        {
          type: 'SELECT',
          label: '所属顾问',
          fieldName: 'telemarketingNo',
          placeholder: '请选择',
          disabled: false,
          itemList: []
        },
        {
          type: 'INPUT_TREE',
          label: '来源渠道',
          fieldName: 'clueSourceId',
          disabled: this.type === 'edit',
          placeholder: '请选择',
          width: 150,
          defaultExpandAll: true,
          initialValue: '',
          itemList: [],
          rules: [{ required: true, message: '请选择来源渠道', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '来源备注',
          fieldName: 'clueSourceRemark',
          maxlength: 32,
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '意向品牌',
          fieldName: 'inteBrand',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.formList.find(item => item.fieldName === 'inteCarSeries').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteCarType').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteOption').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
            this.changeBrandSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '意向车系',
          fieldName: 'inteCarSeries',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.formList.find(item => item.fieldName === 'inteCarType').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteOption').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
            this.changeSeriesSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '意向车型',
          fieldName: 'inteCarType',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteOption').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
            this.changeModelSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '意向配置',
          fieldName: 'inteYearStyle',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.formList.find(item => item.fieldName === 'inteOption').initialValue = '';
            this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
            this.changeOptionSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '意向选装',
          fieldName: 'inteOption',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
            this.changeColorSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '意向颜色',
          fieldName: 'inteColour',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          hidden: true,
          label: '产品ID',
          fieldName: 'productId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'DATE',
          label: '采集时间',
          fieldName: 'acquisitionTime',
          dateType: 'datetime',
          // format: 'yyyy-MM-DD HH:mm',
          placeholder: '请选择'
        },
        {
          type: 'DATE',
          label: '预购日期',
          fieldName: 'bookingDate',
          dateType: 'exactdate',
          placeholder: '请选择'
        },
        {
          type: 'SELECT',
          label: '线索类型',
          fieldName: 'clueType',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictList('7019')
        },
        {
          type: 'SELECT',
          label: '省',
          fieldName: 'provinceId',
          // fieldName: 'province',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: val => {
            console.log('provinceId', val);
            if (val == 3662) {
              this.formList.find(item => item.fieldName === 'city').itemList = [{ text: '台湾', value: 3662 }];
              this.formList.find(item => item.fieldName === 'county').itemList = [{ text: '台湾', value: 3662 }];
            } else if (val == 3663) {
              this.formList.find(item => item.fieldName === 'city').itemList = [{ text: '香港', value: 3663 }];
              this.formList.find(item => item.fieldName === 'county').itemList = [{ text: '香港', value: 3663 }];
            } else if (val == 3664) {
              this.formList.find(item => item.fieldName === 'city').itemList = [{ text: '澳门', value: 3664 }];
              this.formList.find(item => item.fieldName === 'county').itemList = [{ text: '澳门', value: 3664 }];
            }
            let city = [];
            this.formList.find(item => item.fieldName === 'city').initialValue = '';
            this.formList.find(item => item.fieldName === 'county').initialValue = '';
            this.listAllData.forEach(x => {
              // 筛选省
              if (x.parentRegionId == val) {
                city.push({ text: x.regionName, value: x.regionId });
                this.formList.find(item => item.fieldName === 'city').itemList = _.uniqBy(city, 'value');
              }
            });
          }
        },
        {
          type: 'SELECT',
          label: '市',
          fieldName: 'city',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: val => {
            // console.log('val',val)
            let cityList = [];
            this.formList.find(item => item.fieldName === 'county').initialValue = '';
            this.listAllData.forEach(x => {
              // 筛选省
              if (x.parentRegionId == val) {
                // console.log('val111',val)
                cityList.push({ text: x.regionName, value: x.regionId });
                this.formList.find(item => item.fieldName === 'county').itemList = _.uniqBy(cityList, 'value');
              }
            });
          }
        },
        {
          type: 'SELECT',
          label: '区',
          // fieldName: 'county',
          fieldName: 'county',
          placeholder: '请选择',
          initialValue: '',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '详细地址',
          selfCols: 2,
          fieldName: 'address',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: 'cc清洗备注',
          selfCols: 2,
          fieldName: 'ccInvalidReason',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          maxlength: 128,
          selfCols: 2,
          rows: 1,
          disabled: false,
          placeholder: '请输入'
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    // 来源渠道限制
    deepListClone(data) {
      let tempList = [];
      // console.log('deepListClone',Object.prototype.toString.call(data),data)
      if (data && data.length && Object.prototype.toString.call(data) == '[object Array]') {
        for (let i in data) {
          if (data[i].children && [].concat(data[i].children).length > 0) {
            tempList[i] = {
              text: data[i].clueName,
              value: data[i].value,
              parentId: data[i].parentId,
              disabled: true,
              businessType: data[i].businessType,
              children: this.deepListClone([].concat(data[i].children))
            };
          } else {
            tempList[i] = {
              text: data[i].clueName,
              value: data[i].value,
              parentId: data[i].parentId,
              disabled: false,
              businessType: data[i].businessType
            };
          }
        }
      }
      return tempList;
    },
    // 来源渠道
    async getClueTree() {
      const res = await queryClueSourceList();
      // const res = await queryClueSourceList({dataType: 70261002});  //只显示线上
      // console.log('来源渠道res', res)
      let treeList = this.deepListClone([].concat(res.data));
      // console.log('处理后来源渠道',treeList)
      this.formList.find(item => item.fieldName === 'clueSourceId').itemList = treeList;
      // if(this.type != 'add'){
      //   this.formList.find(item => item.fieldName ==='clueSourceId').initialValue=this.rowData.clueSourceId
      // }
    },
    // 意向车型
    async getDictBrandList() {
      const res = await getBrandList();
      // console.log("品牌YX",res)
      if (res.resultCode === 200) {
        this.formList.find(item => item.fieldName === 'inteBrand').itemList = res.data.map(x => ({ value: `${x.brandId}`, text: x.brandName }));
      }
    },
    async changeBrandSelect(brandsid) {
      if (!brandsid) {
        this.formList.find(item => item.fieldName === 'inteCarSeries').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteCarSeries').itemList = [];
        this.formList.find(item => item.fieldName === 'inteCarType').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteCarType').itemList = [];
        this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteYearStyle').itemList = [];
        let inteOption = this.formList.find(item => item.fieldName === 'inteOption');
        inteOption.initialValue = '';
        inteOption.itemList = [];
        this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteColour').itemList = [];
      } else {
        const res = await getSeriesList(brandsid);
        if (res.resultCode === 200) {
          // console.log("车系YX",res)
          this.formList.find(item => item.fieldName === 'inteCarSeries').itemList = res.data.map(x => ({ value: `${x.seriesId}`, text: x.seriesName }));
        }
      }
    },
    async changeSeriesSelect(seriessid) {
      const brandsid = this.formList.find(item => item.fieldName === 'inteBrand').initialValue;
      if (!brandsid || !seriessid) {
        this.formList.find(item => item.fieldName === 'inteCarType').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteCarType').itemList = [];
        this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteYearStyle').itemList = [];
        let inteOption = this.formList.find(item => item.fieldName === 'inteOption');
        inteOption.initialValue = '';
        inteOption.itemList = [];
        this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteColour').itemList = [];
      } else {
        const res = await getModelList(brandsid, seriessid);
        if (res.resultCode === 200) {
          // console.log("车型YX",res)
          this.formList.find(item => item.fieldName === 'inteCarType').itemList = res.data.map(x => ({ value: `${x.modelId}`, text: x.modelName }));
        }
      }
    },
    async changeModelSelect(modelId) {
      const brandsid = this.formList.find(item => item.fieldName === 'inteBrand').initialValue;
      const seriessid = this.formList.find(item => item.fieldName === 'inteCarSeries').initialValue;
      if (!brandsid || !seriessid || !modelId) {
        this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteYearStyle').itemList = [];
        let inteOption = this.formList.find(item => item.fieldName === 'inteOption');
        inteOption.initialValue = '';
        inteOption.itemList = [];
        this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteColour').itemList = [];
      } else {
        const res = await getPackageList(modelId);
        if (res.resultCode === 200) {
          // console.log("配置YX",res)
          this.formList.find(item => item.fieldName === 'inteYearStyle').itemList = res.data.map(x => ({ value: `${x.packageId}`, text: x.configName }));
        }
      }
    },
    //变更选装选择框
    async changeOptionSelect(packageId) {
      const brandsid = this.formList.find(item => item.fieldName === 'inteBrand').initialValue;
      const seriessid = this.formList.find(item => item.fieldName === 'inteCarSeries').initialValue;
      const modelId = this.formList.find(item => item.fieldName === 'inteCarType').initialValue;
      if (!brandsid || !seriessid || !modelId || !packageId) {
        let inteOption = this.formList.find(item => item.fieldName === 'inteOption');
        inteOption.initialValue = '';
        inteOption.itemList = [];
        this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteColour').itemList = [];
      } else {
        const res = await getOptionList(packageId);
        if (res.resultCode === 200) {
          // console.log("颜色YX",res)
          this.formList.find(item => item.fieldName === 'inteOption').itemList = res.data.map(x => ({ value: `${x.optionId}`, text: x.optionName }));
        }
      }
    },
    //变更颜色选择框
    async changeColorSelect(optionId) {
      const brandsid = this.formList.find(item => item.fieldName === 'inteBrand').initialValue;
      const seriessid = this.formList.find(item => item.fieldName === 'inteCarSeries').initialValue;
      const modelId = this.formList.find(item => item.fieldName === 'inteCarType').initialValue;
      const packageId = this.formList.find(item => item.fieldName === 'inteYearStyle').initialValue;
      if (!brandsid || !seriessid || !modelId || !packageId || !optionId) {
        this.formList.find(item => item.fieldName === 'inteColour').initialValue = '';
        this.formList.find(item => item.fieldName === 'inteColour').itemList = [];
      } else {
        const res = await getColorsList(optionId);
        //zhangtan
        if (res.resultCode === 200) {
          // console.log("颜色YX",res)
          this.formList.find(item => item.fieldName === 'inteColour').itemList = res.data.map(x => ({ value: `${x.productId}`, text: x.colorName }));
        }
      }
    },
    // 城市
    async getCityList() {
      //  console.log(this.province_id,this.city_id,"this.formList[89]")
      await getlistAllData().then(res => {
        // console.log('城市', res)
        let province = [];
        let initCity = [];
        let initCounty = [];
        this.listAllData = res.data;
        this.listAllData.forEach(x => {
          // 筛选省
          if (x.parentRegionId == null) {
            province.push({ text: x.regionName, value: `${x.regionId}` });
          }
          // 市
          if (x.parentRegionId == this.province_id) {
            initCity.push({ text: x.regionName, value: `${x.regionId}` });
          }
          if (x.parentRegionId == this.city_id) {
            initCounty.push({ text: x.regionName, value: `${x.regionId}` });
          }
        });
        this.formList.find(item => item.fieldName === 'provinceId').itemList = province;
        this.formList.find(item => item.fieldName === 'city').itemList = initCity;
        this.formList.find(item => item.fieldName === 'county').itemList = initCounty;
      });
    },
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let oldDate = '';
      (oldDate = this.formList.find(x => x.fieldName === 'bookingDate').initialValue
        ? new Date(this.formList.find(x => x.fieldName === 'bookingDate').initialValue.replace(new RegExp('-', 'gm'), '/')).getTime()
        : ''),
        console.log('oldDate', oldDate);
      if (oldDate) {
        let newDate = forDates(oldDate);
        console.log('newDate', newDate);
        this.saveData.bookingDate = newDate;
      }
      // console.log("this.consultsList ",this.consultsList )
      this.consultsList.forEach(item => {
        if (this.saveData.telemarketingNo == item.value) {
          this.saveData['orgId'] = item.orgId;
        }
      });
      console.log('保存11111', this.saveData);
      if (this.saveData !== null) {
        let res = {};
        if (this.type === 'add') {
          this.saveData.productId = this.saveData.inteColour;
          res = await addNewClue(this.saveData);
        }
        if (res.resultCode === 200) {
          this.closeDialog('refresh');
          this.$message.success('保存成功!');
        }
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    }
  }
};
</script>

<style lang="less" scoped>
</style>
